layui.use(['layer','table','form'], function(args){
    layer = layui.layer;
    table = layui.table;
    form = layui.form;
    form.on('submit(group-add-from)', function(data){
        if (addFormType==2)
            update();
        else if (addFormType==1)
            add(data.form);
        return false;
    });


});

/**
 * 添加用户组下的用户
 * @param groupId
 */
function addUserWindow(groupId,groupName) {
    layer.open({
        type: 1,
        title: groupName+'添加用户', //不显示标题
        content: $('#user-grid-table'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        area:['500px','400px'],
        btn:['添加','取消'],
        end:function () {
            //窗口销毁时把窗口的表格也删除了，不然会显示出主页面里的
            $('#user-grid-table + div.layui-table-view').remove();
        },
        yes:function (index,layero) {
            var selectedData = table.checkStatus('user-grid').data;
            if (!selectedData|| selectedData.length==0){
                layer.alert("请至少选择一个用户");
                return;
            }
            var userIds=[];
            for(var i in selectedData){
                userIds.push(selectedData[i].id);
            }
            var loadIndex = layer.load(2);
            $.ajax({
                url: basePath+ "process/group/addUserByIds.do",
                data: {userIds:userIds.join(","),groupId:groupId},
                type:'post',
                dataType: 'json',
                success: function (data, textStatus) {
                    layer.close(loadIndex);
                    layer.alert(data.message,function(index ){
                        if (data.success){
                            table.reload('user-grid');
                        }
                        layer.close(index);
                    });
                }
            });
        },
        success: function(layero, index){
            table.render({
                elem: '#user-grid-table' //指定原始表格元素选择器（推荐id选择器）
                ,height: 300 //容器高度
                ,cols: [[//设置表头
                    {checkbox:true}
                    ,{field: 'firstName', title: '用户名', width: 120}
                    ,{field: 'lastName', title: '姓名', width: 120}
                    ,{field: 'email', title: '邮箱', width: 206}
                ]]
                ,url:basePath+'process/user/list.json'
                ,where:{groupId:groupId,notIn:true}
                ,id:'user-grid'
                ,request:{pageName:'pageNum',limitName:'pageSize'}
                ,response:{statusName:'status',statusCode:200,countName:'total',dataName:'list'}
                ,limit:99999
            });
        }
    });

}
/**
 * 移除用户组下的用户
 * @param groupId
 */
function removeUserWindow(groupId,groupName) {
   layer.open({
        type: 1,
        title: groupName+'移除用户', //不显示标题
        content: $('#user-grid-table'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        area:['500px','400px'],
        btn:['移除','关闭'],
       end:function () {
            //窗口销毁时把窗口的表格也删除了，不然会显示出主页面里的
           $('#user-grid-table + div.layui-table-view').remove();
       },
       yes:function (index,layero) {
           var selectedData = table.checkStatus('user-grid').data;
           if (!selectedData|| selectedData.length==0){
               layer.alert("请至少选择一个用户");
               return;
           }
           var userIds=[];
           for(var i in selectedData){
               userIds.push(selectedData[i].id);
           }
           var loadIndex = layer.load(2);
           $.ajax({
               url: basePath+ "process/group/removeUserByIds.do",
               data: {userIds:userIds.join(","),groupId:groupId},
               type:'post',
               dataType: 'json',
               success: function (data, textStatus) {
                   layer.close(loadIndex);
                   layer.alert(data.message,function(index ){
                       if (data.success){
                           table.reload('user-grid');
                       }
                       layer.close(index);
                   });
               }
           });
       },
        success: function(layero, index){
            table.render({
                elem: '#user-grid-table' //指定原始表格元素选择器（推荐id选择器）
                ,height: 300 //容器高度
                ,cols: [[//设置表头
                    {checkbox:true}
                    ,{field: 'firstName', title: '用户名', width: 120}
                    ,{field: 'lastName', title: '姓名', width: 120}
                    ,{field: 'email', title: '邮箱', width: 206}
                ]]
                ,url:basePath+'process/user/list.json?groupId='+groupId
                ,id:'user-grid'
                ,request:{pageName:'pageNum',limitName:'pageSize'}
                ,response:{statusName:'status',statusCode:200,countName:'total',dataName:'list'}
                ,limit:99999
            });
        }
    });

}



var addWindwodIndex;
function showAddWindow(type) {
    addFormType = type;
    var title;
    if (type==2){//修改
        var selectedData = table.checkStatus('group-grid').data;
        if (!selectedData|| selectedData.length==0){
            layer.alert("请选择一条要修改的数据");
            return;
        }else if (selectedData.length>1){
            layer.alert("只能选择一条要修改的数据");
            return;
        }
        title = '修改';
        $('#addForm').autofill(selectedData[0]);
        $('#addForm select').val(selectedData[0].positionId)
        $('#addForm input[name=id]').attr("readonly",true);
    }else{
        title = '新增';
        $('#addForm input[name=id]').removeAttr("readonly");
    }
    addWindwodIndex = layer.open({
        type: 1,
        title: title, //不显示标题
        content: $('#addForm'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        area:['500px'],
        end:function () {
            $('#addForm button:reset').click();
        }
    });
    form.render();
}
function del(){
    var selectedData = table.checkStatus('group-grid').data;
    if (!selectedData || selectedData.length==0){
        layer.alert("请选择要删除的数据");
        return;
    }
    layer.confirm('确定要删除这些用户组?', {icon: 3, title:'提示'}, function(index){
        var ids=[];
        for(var i in selectedData){
            ids.push(selectedData[i].id);
        }
        var loadIndex=layer.load(2);
        $.ajax({
            url: basePath+ "process/group/delete.do",
            data: {ids:ids.join(",")},
            type:'post',
            dataType: 'json',
            success: function (data, textStatus) {
                layer.close(loadIndex);
                layer.alert(data.message,function(index ){
                    if (data.success){
                        table.reload('group-grid');
                    }
                    layer.close(index);
                })
            }
        });
        layer.close(index);
    });

};
function add(form) {
    var loadIndex=layer.load(2);
    $.ajax({
        url: basePath+"process/group/add.do",
        data: $(form).serialize(),
        dataType: 'json',
        type:'POST',
        success: function (data, textStatus) {
            layer.close(loadIndex);
            layer.alert(data.message,function(index){
                if (data.success){
                    layer.close(addWindwodIndex);
                    addWindwodIndex =null;
                    table.reload('group-grid');
                }
                layer.close(index);
            });
        }
    })
}
function update(){
    var loadIndex=layer.load(2);
    $.ajax({
        url: basePath+"/process/group/update.do",
        data: $("#addForm").serialize(),
        dataType: 'json',
        type:'post',
        success: function (data, textStatus) {
            layer.close(loadIndex);
            layer.alert(data.message,function (index) {
                if (data.success){
                    layer.close(addWindwodIndex);
                    addWindwodIndex =null;
                    table.reload('group-grid');
                }
                layer.close(index);
            });

        }
    });
}